<template>
	<view class="chamber-page">
		<!-- 自定义导航栏 -->
		<u-navbar leftIconColor='#FFFFFF' title="商(协)会联盟" titleStyle='font-weight:bold;color:white;font-size:36rpx' bgColor='transparent' :autoBack="true"></u-navbar>

		<!-- 顶部背景区域 -->
		<view class="header-bg">
			<image class="header-bg-image" src="https://yjgs.jsonbug.com/storage/default/20250312/17421060569200705625.png" />
		</view>
		
		<view style="height: 30rpx;"></view>
		
		<!-- 轮播图 -->
		<view class="swiper-container">
			<u-swiper height='180' :list="swiperList" keyName="image" :effect3d="true" :previousMargin="30"
				:nextMargin="30" circular :autoplay="true" radius="10" bgColor="transparent" :interval="3000"
				indicatorActiveColor="#ff0000" indicatorInactiveColor="rgba(255,255,255,0.5)" indicator></u-swiper>
		</view>

		<!-- 搜索和创建区域 -->
		<view class="search-section">
			<view class="search-box">
				<image class="search-icon" @click="handleSearch" src="https://yjgs.jsonbug.com/storage/default/20250312/17421060569500660098.png" />
				<input type="text" v-model="searchText" @input="debounceSearch" @confirm="handleSearch"
					class="search-input" placeholder="请输入商(协)会名称" />
				<text v-if="searchText" @click="clearSearch" class="clear-icon">×</text>
			</view>
			<view class="create-btn" @click="handleCreate">
				<text class="create-text">免费创建商(协)会平台</text>
			</view>
		</view>

		<!-- 标签切换 -->
		<view class="tab-section">
			<view class="tab-bar">
				<text class="tab-item" :class="{'active': activeTab === 0}" @click="switchTab(0)">友好商(协)会</text>
				<text class="tab-item" :class="{'active': activeTab === 1}" @click="switchTab(1)">我的商(协)会</text>
			</view>
			<view class="tab-indicator" :style="{transform: `translateX(${activeTab * 200}rpx)`}"></view>
		</view>

		<!-- 商(协)会列表 -->
		<view class="chamber-list">
			<view v-if="chamberList.length === 0" class="empty-list">
				<text class="empty-text">暂无商(协)会数据</text>
			</view>
			<view @click="toPage(item)" class="chamber-item" v-for="(item, index) in chamberList" :key="index">
				<view class="chamber-logo-wrapper">
					<image class="chamber-logo" mode="aspectFill" :src="$timer.ensureUrl(item.logo) || 'https://ide.code.fun/api/image?token=67d66df3defdb1001118b84f&name=445617016e20a36b787398650c7a3599.png'" />
				</view>
				<view class="chamber-info">
					<text class="chamber-name">{{item.nickname || ''}}</text>
					<text class="chamber-date">成立时间：{{formatDate(item.set_time)}}</text>
					<text class="chamber-members">商(协)会成员：{{item.number || 0}}{{item.number > 99 ? '+' : ''}}</text>
					<view class="detail-btn"><text class="detail-text">查看详情</text></view>
				</view>
			</view>
		</view>

		<!-- 加载更多 -->
		<uni-load-more :status="status" />
	</view>
</template>

<script>
	import {
		mapGetters
	} from "vuex";
	import {
		configMap
	} from "@/utils";
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		comList,
		comConfig
	} from '@/api/extend.js';

	export default {
		components: {},
		props: {},
		data() {
			return {
				items: [null, null, null, null],
				searchText: '',
				activeTab: 0, // 0: 未加入的商(协)会, 1: 我的商(协)会
				chamberList: [], // 商(协)会列表数据
				swiperList: [],
				status: 'loading', // more loading noMore
				current_page: 1,
				limit: 10,
				searchTimer: null // 用于防抖的定时器
			};
		},
		computed: configMap({}, mapGetters(['isLogin', 'uid', 'userInfo'])),
		onLoad() {
			this.getChamberList();
			this.getSwiperList();
		},
		onReachBottom() {
			if (this.status == 'noMore') return;
			this.current_page++;
			this.getChamberList();
		},
		// #ifdef MP
		onShareAppMessage: function() {
			wx.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage', 'shareTimeline']
			})
			return {
				title: '商(协)会联盟',
				path: `pages/extend/chamber/chamber_list?uid=${this.uid || -1}`,
			}
		},
		onShareTimeline: function() {
			return {
				title: '商(协)会联盟',
				query: {
					uid: this.uid
				},
				imageUrl: ''
			}
		},
		// #endif
		methods: {
			// 获取轮播图数据
			getSwiperList() {
				const params = {
					com_id: "0",
					type: "1"
				};
				comConfig(params).then(res => {
					if (res.status === 200 && res.data) {
						// 确保数据格式与组件要求一致
						this.swiperList = res.data || [];
						// 使用$timer.ensureUrl处理图片URL，与其他图片处理保持一致
						this.swiperList.forEach(item => {
							if (item.image) {
								item.image = this.$timer.ensureUrl(item.image);
							}
						});
					} else {
						uni.showToast({
							title: res.message || '获取轮播图失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.showToast({
						title: '网络异常，请稍后重试',
						icon: 'none'
					});
					console.error('获取轮播图失败', err);
				});
			},

			// 获取商(协)会列表
			getChamberList() {
				const params = {
					type: Number(this.activeTab) + 1, // 1: 未加入的商(协)会, 2: 我的商(协)会
					limit: this.limit,
					page: this.current_page
				};

				// 添加搜索参数
				if (this.searchText && this.searchText.trim()) {
					params.name = this.searchText.trim();
				}

				comList(params).then(res => {
					if (res.status === 200 && res.data) {
						const data = res.data.data || [];
						this.current_page = res.data.current_page;

						if (data.length < this.limit) {
							this.status = 'noMore';
						} else {
							this.status = 'more';
						}

						if (this.current_page === 1) {
							this.chamberList = data;
						} else {
							this.chamberList = [...this.chamberList, ...data];
						}
					} else {
						uni.showToast({
							title: res.message || '获取商(协)会列表失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.showToast({
						title: '网络异常，请稍后重试',
						icon: 'none'
					});
					console.error('获取商(协)会列表失败', err);
				});
			},

			// 搜索触发
			handleSearch() {
				this.current_page = 1; // 重置为第一页
				this.status = 'loading';
				this.getChamberList();
			},

			// 防抖搜索
			debounceSearch() {
				// 清除之前的定时器
				if (this.searchTimer) {
					clearTimeout(this.searchTimer);
				}

				// 设置新的定时器，500ms后执行搜索
				this.searchTimer = setTimeout(() => {
					this.handleSearch();
				}, 500);
			},

			// 清空搜索
			clearSearch() {
				this.searchText = '';
				this.current_page = 1; // 重置为第一页
				this.status = 'loading';
				this.getChamberList();
			},

			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '';
				// 处理日期格式，确保正确显示
				try {
					// 尝试转换日期
					const date = new Date(dateStr);
					if (isNaN(date.getTime())) {
						return dateStr; // 如果转换失败，返回原始字符串
					}
					return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
				} catch (e) {
					return dateStr;
				}
			},

			toPage(item) {
				this.$store.commit('SET_ChamberObj', item)
				uni.navigateTo({
					url: `/pages/extend/chamber/chamber_home?cid=${item.id || ''}`
				})
			},

			handleCreate() {
				if (!this.isLogin) {
					toLogin();
					return;
				}
				uni.navigateTo({
					url: '/pages/extend/chamber/create_chamber'
				})
			},

			switchTab(index) {
				if (this.activeTab !== index) {
					this.activeTab = index;
					this.current_page = 1; // 切换标签时重置页码
					this.getChamberList(); // 切换标签时重新获取数据
				}
			}
		},
	};
</script>

<style scoped lang="css">
	/* 页面基础样式 */
	.chamber-page {
		background-color: #f7f7f7;
		min-height: 100vh;
		width: 100%;
		position: relative;
	}

	/* 顶部背景区域 */
	.header-bg {
		background-image: linear-gradient(172.5deg, #ff0000 48.2%, rgba(196, 0, 1, 0) 80%);
		height: 420rpx;
		width: 100%;
		position: relative;
		overflow: hidden;
	}

	.header-bg-image {
		opacity: 0.2;
		width: 100%;
		height: 100%;
		position: absolute;
		left: 0;
		top: 0;
		object-fit: cover;
	}

	/* 轮播图区域 */
	.swiper-container {
		position: relative;
		margin-top: -260rpx;
		padding: 0 20rpx;
		z-index: 10;
	}

	/* 搜索和创建区域 */
	.search-section {
		padding: 30rpx 20rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		background-image: linear-gradient(0deg, #ffffff 0%, rgba(255, 255, 255, 0) 100%);
	}

	.search-box {
		flex: 1;
		display: flex;
		flex-direction: row;
		align-items: center;
		background-color: #ffffff;
		border-radius: 20rpx;
		height: 85rpx;
		padding: 0 20rpx;
		border: solid 2rpx #ffc2c2;
		box-shadow: 0 4rpx 8rpx rgba(255, 209, 209, 0.5);
	}

	.search-icon {
		width: 32rpx;
		height: 32rpx;
	}

	.search-input {
		flex: 1;
		height: 85rpx;
		line-height: 85rpx;
		font-size: 28rpx;
		padding: 0 20rpx;
		color: #333;
	}

	.clear-icon {
		font-size: 40rpx;
		color: #999;
		padding: 0 15rpx;
		line-height: 85rpx;
	}

	.create-btn {
		margin-left: 20rpx;
		width: 290rpx;
		height: 85rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-image: linear-gradient(295deg, #d60000 3.7%, #d64f00 93.3%);
		border-radius: 20rpx;
		box-shadow: 0 4rpx 8rpx rgba(255, 163, 163, 0.5);
		border: solid 2rpx #ffffff;
	}

	.create-text {
		color: #ffffff;
		font-size: 28rpx;
		font-weight: bold;
	}

	/* 标签切换 */
	.tab-section {
		padding: 10rpx 30rpx 0;
		margin-bottom: 10rpx;
		position: relative;
	}

	.tab-bar {
		display: flex;
		flex-direction: row;
		align-items: center;
		padding-bottom: 15rpx;
	}

	.tab-item {
		font-size: 30rpx;
		color: #666666;
		padding: 10rpx 0;
		margin-right: 40rpx;
		position: relative;
	}

	.tab-item.active {
		color: #d60000;
		font-weight: bold;
		font-size: 32rpx;
	}

	.tab-indicator {
		position: absolute;
		bottom: 0;
		left: 30rpx;
		background-color: #d60000;
		width: 60rpx;
		height: 6rpx;
		border-radius: 3rpx;
		transition: transform 0.3s ease;
	}

	/* 商(协)会列表 */
	.chamber-list {
		padding: 20rpx;
	}

	.chamber-item {
		display: flex;
		flex-direction: row;
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 30rpx 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.chamber-logo-wrapper {
		width: 160rpx;
		height: 160rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 20rpx;
		overflow: hidden;
		background-color: #ffffff;
		border: 1rpx solid #f0f0f0;
	}

	.chamber-logo {
		width: 134rpx;
		height: 134rpx;
	}

	.chamber-info {
		flex: 1;
		margin-left: 20rpx;
		display: flex;
		flex-direction: column;
	}

	.chamber-name {
		font-size: 34rpx;
		color: #333333;
		font-weight: 500;
		margin-bottom: 20rpx;
	}

	.chamber-date, .chamber-members {
		font-size: 26rpx;
		color: #666666;
		margin-bottom: 15rpx;
	}

	.detail-btn {
		margin-top: 10rpx;
		width: 120rpx;
		height: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border: solid 1rpx #ff2626;
		border-radius: 8rpx;
	}

	.detail-text {
		font-size: 22rpx;
		color: #ff2626;
	}

	/* 空状态 */
	.empty-list {
		padding: 100rpx 0;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.empty-text {
		color: #999;
		font-size: 28rpx;
	}
</style>